package com.gem.eolane.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gem.eolane.config.AppConfig;
import com.gem.eolane.entity.Dict;
import com.gem.eolane.entity.Order;
import com.gem.eolane.entity.PcbOffer;
import com.gem.eolane.entity.User;
import com.gem.eolane.mapper.OrderMapper;
import com.gem.eolane.mapper.PcbOfferMapper;
import com.gem.eolane.utils.DictUtils;
import com.gem.eolane.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PcbOfferService extends ServiceImpl<PcbOfferMapper, PcbOffer> {
    @Autowired
    private PcbOfferMapper pcbOfferMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DictUtils dictUtils;
    @Autowired
    private WebUtils webUtils;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private AppConfig appConfig;

    /*计算价格*/
    public PcbOffer pcbCount(PcbOffer pcbOffer){
        /*查出材料字典列表*/
        List<Dict> dicts = dictUtils.getAllDictList();

        /*系数 1-不可为空，2-可为空*/
        Double L = null;  //层L
        Double LT = null; //层LT
        Double A = null;
        Double B = null;
        Double C = pcbOffer.getLength();
        Double D = pcbOffer.getWidth();
        Double E = null;
        Double F = null;
        Double G = null;
        Double H = pcbOffer.getPcsPanel();
        Double H2 = null;
        Double I = pcbOffer.getPanelLength();//2
        Double J = pcbOffer.getPanelWidth();//2
        Double Q = pcbOffer.getQutantity();
        Double X = null;
        Double Y = null;//加急

        String valueH2 = "";
        /*判断H2*/
        if(H != null) {
            if(H<=10){
                valueH2 = "a";
            }else if(H>=11 && H<=30){
                valueH2 = "b";
            }else if(H>= 31 && H <=50){
                valueH2 = "c";
            }else if(H>=51 && H<=100){
                valueH2 = "d";
            }
        }

        /*系数集合*/
        List<Double> xsList = new ArrayList<>();

        for (Dict dict: dicts){
            String value = dict.getValue();
            String type = dict.getType();
            Double xs = dict.getXs();
            /*层数系数*/
            if (pcbOffer.getLayerNumber().equals(value)&&type.equals("number_layers")){
                L = xs;
                LT = dict.getXs2();
            }
            /*材料系数*/
            if(pcbOffer.getMaterial().equals(value)&&type.equals("material")){
                A = xs;
            }
            /*厚度系数*/
            if(pcbOffer.getThickness().equals(value)&&type.equals("thickness")){
                B = xs;
            }
            /*表面处理系数*/
            if(pcbOffer.getSurfactTreatment().equals(value)&&type.equals("surfact_treatment")){
                E = xs;
            }
            /*外基铜系数*/
            if(pcbOffer.getEbct().equals(value)&&type.equals("ebct")){
                F = xs;
            }
            /*内基铜厚度系数*/
            if(pcbOffer.getIbct().equals(value)&&type.equals("ibct")){
                G = xs;
            }
            /*付款方式系数*/
            if (pcbOffer.getCurrency().equals(value) && type.equals("currency")) {
                X = xs;
            }
            /*PCS/PANEL*/
            if(valueH2.equals(value) && type.equals("pcs")){
                H2 = xs;
            }
            /*加急*/
            if(pcbOffer.getUrgent().equals(value)&&type.equals("urgent")){
                Y = xs;
            }
        }
        /*加入系数集合*/
        xsList.add(L);
        xsList.add(LT);
        xsList.add(A);
        xsList.add(B);
        xsList.add(C);
        xsList.add(D);
        xsList.add(E);
        xsList.add(F);
        xsList.add(G);
        xsList.add(H);
        xsList.add(H2);
        xsList.add(Q);
        xsList.add(X);

        /*为空标识符*/
        int flag = 0;
        for (Double xs: xsList){
            System.out.println(xs);
            if(xs == null){
                flag++;
            }
        }


        /*计算价格*/
        if(flag != 0){
            /*不用计算*/
            pcbOffer.setTprice(0.0);
            System.out.println("超出值不计算！");
        }else {
            /**
             * 计算
            */
            //整批数量
            Double Qty = null;
            Double num = Math.pow(10,6);
            if(I!=null||J!=null){
                Qty = I*J/H*Q/num;
            }else{
                Qty = C*D*Q/num;
            }
            System.out.println("qty:"+Qty);
            /*单品价格*/
            BigDecimal t = new BigDecimal(Qty*L*A*B*E*F*G*H2);
            Double Tprice = t.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            System.out.println("Tprice:"+Tprice);
            pcbOffer.setTprice(Tprice);

            /*运费*/
            BigDecimal f = new BigDecimal(Qty*B*3*235);
            Double fcost = f.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            Double Fcost = Math.max(fcost,180);
            System.out.println("Fcost:"+Fcost);
            pcbOffer.setFcost(Fcost);

            /*工程费*/
            Double Scost = L*1.2;
//            System.out.println("Scost:"+Scost);
            pcbOffer.setScost(Scost);

            /*单价*/
            BigDecimal u = new BigDecimal((Tprice+Fcost+Scost)/Q);
            Double Uprice = u.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//            System.out.println("单价Uprice:"+Uprice);
            /*转换币种*/
            BigDecimal a = new BigDecimal(Uprice/X);
            Uprice = a.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//            System.out.println("转换币种Uprice:"+Uprice);
            pcbOffer.setUprice(Uprice);

            /*加急价*/
            Double Uprice2 = Uprice*Y;
            pcbOffer.setUprice2(Uprice2);
            /*总价格*/
            BigDecimal b = new BigDecimal(Uprice*Q);
            Double price = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            pcbOffer.setPrice(price);

            System.out.println("price:"+price);
            /*加急总价*/
            BigDecimal c = new BigDecimal(Uprice2*Q);
            Double price2 = c.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            pcbOffer.setPrice2(price2);
            System.out.println("price2:"+price);
        }


        /*id赋值*/
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String str = sdf.format(new Date());
        Integer count = pcbOfferMapper.selectCount(new QueryWrapper<>()) +1;
        pcbOffer.setId(str+count);

        return pcbOffer;

    }


    /*保存订单*/
    public void saveOrder(PcbOffer pcbOffer, User user) throws UnsupportedEncodingException {
        /*用户id*/
        pcbOffer.setUserId(user.getId());
        /*生成order*/
        Order order = new Order();
        /*单号*/
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        String str = sdf.format(new Date());
        Integer count = orderMapper.selectCount(new QueryWrapper<>());
        Integer num = 1000+count;
        order.setOrderNumber(str+count);
        /*用户id*/
        order.setUserId(user.getId());
        /*orderID*/
        order.setOrderId(pcbOffer.getId());
        /*类型*/
        order.setType(1);
        /*创建时间*/
        Date date = new Date();
        pcbOffer.setCreateTime(date);
        /*保存pcboffer*/
      /*  System.out.println("时间：" + pcbOffer.getCreateTime());*/
        pcbOfferMapper.insert(pcbOffer);
        /*保存订单*/
        orderMapper.insert(order);


     //*编辑微信发送信息*//*
        String titleStr = "PCB报价信息";
        String msgStr = "用户："+user.getUserName()+",电话："+user.getPhoneNumber()+",单号："+order.getOrderNumber()+",价格："+pcbOffer.getPrice()+",数量："+pcbOffer.getQutantity();
        String urlStr = "<http://localhost:9000/eolane/pcb/view?id=9>";
        String msg = URLEncoder.encode(msgStr,"utf8");
        String title = URLEncoder.encode(titleStr,"utf8");
        String url = URLEncoder.encode("http://localhost:9000/eolane/pcb/view?id=9","utf8");
       /* webUtils.sendPost("http://ebpm.eolane.cn/API/SendWeixin",
                "TagName=3&Title="+title+"&Url="+url+"&Msg="+msg+"&App=equote&VeriCode=gemEqu0te%26");*/

        //*发送邮箱marketing@eolane.cn*//*
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(appConfig.mail);
        message.setTo(appConfig.mail2);
        message.setSubject(titleStr);
        message.setText(msgStr+"连接："+urlStr);
        mailSender.send(message);

    }



}
